package com.play.ballen.utils;


import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.widget.TextView;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;

public class URLImageParser implements Html.ImageGetter {
    TextView mTextView;
    public URLImageParser(TextView textView) {
        this.mTextView = textView;
    }
    @Override
    public Drawable getDrawable(String source) {
        final URLDrawable urlDrawable = new URLDrawable();
        Glide.with(mTextView.getContext())
                .asBitmap()
                .sizeMultiplier(0.6f)
                .sizeMultiplier(0.3f)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .load(source)
                .into(new SimpleTarget<Bitmap>() {

                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
//                        urlDrawable.bitmap = resource;
//                        urlDrawable.setBounds(0, 0, resource.getWidth(), resource.getHeight());
//                        mTextView.invalidate();
//                        mTextView.setText(mTextView.getText());
                        urlDrawable.bitmap = resource;
                        // Calculate the height while maintaining the aspect ratio
                        int width = mTextView.getWidth();
                        int height = (int) (resource.getHeight() * ((float) width / resource.getWidth()));
                        urlDrawable.setBounds(0, 0, width, height);
                        mTextView.invalidate();
                        mTextView.setText(mTextView.getText());
                    }
                });
        return urlDrawable;
    }
    public class URLDrawable extends BitmapDrawable {
        protected Bitmap bitmap;
        @Override
        public void draw(Canvas canvas) {
            if (bitmap != null) {
                canvas.drawBitmap(bitmap, 0, 0, getPaint());
                try {
                    canvas.drawBitmap(bitmap, 0, 0, getPaint());
                }catch (Exception e){
                }
            }
        }
    }
}


